import 'package:flutter/material.dart';
import 'package:flutter_food/core/model/category_model.dart';
import 'package:flutter_food/core/model/meal_model.dart';
import 'package:flutter_food/core/viewmodel/meal_view_model.dart';
import 'package:flutter_food/ui/widgets/meal_item.dart';
import 'package:provider/provider.dart';
import 'package:collection/collection.dart';

class MealContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return
        //UseConsumerContent()
        UseSelectorContent();
  }
}

// 使用Selector
class UseSelectorContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final category = ModalRoute.of(context).settings.arguments as CategoryModel;
    return Selector<MealViewModel, List<MealModel>>(
        builder: (ctx, meals, child) {
          return ListView.builder(
              itemCount: meals.length,
              itemBuilder: (ctx, index) {
                return MealItem(meals[index]);
              });
        },
        // 当新旧数据不同时，则通知刷新
        shouldRebuild: (prev, next) => !ListEquality().equals(prev, next),
        // 数据模型转换、筛选
        selector: (ctx, vm) => vm.meals
            .where((element) => element.categories.contains(category.id))
            .toList());
  }
}

/// 使用Consumer缺点
/// 1.每次数据发生改变都会重新build影响性能
/// 2.使用selector直接就内置过滤方法
class UseConsumerContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final category = ModalRoute.of(context).settings.arguments as CategoryModel;
    return Consumer<MealViewModel>(builder: (ctx, mealVM, child) {
      // 获取全部meal
      final mealList = mealVM.meals
          .where((element) => element.categories.contains(category.id))
          .toList();
      return ListView.builder(
          itemCount: mealList.length,
          itemBuilder: (ctx, index) {
            return ListTile(
              title: Text(mealList[index].title),
            );
          });
    });
  }
}
